import { create, all } from 'mathjs'

const config = {
  number: 'BigNumber',
  precision: 20
}

const math = create(all, config)

function toNonExponential(num) {
  var m = num.toExponential().match(/\d(?:\.(\d*))?e([+-]\d+)/)
  return num.toFixed(Math.max(0, (m[1] || '').length - m[2]))
}

export function numberAdd(...arg) {
  let sum = 0
  arg.forEach((ele, index) => {
    if (index === 0) {
      sum = math.add(ele, 0)
    } else {
      if (ele) {
        sum = math.add(math.bignumber(sum), math.bignumber(ele))
      }
    }
  })
  return toNonExponential(sum)
}

export function numberSub(...arg) {
  let sum = 0
  arg.forEach((ele, index) => {
    if (index === 0) {
      sum = math.subtract(math.bignumber(ele), math.bignumber(0))
    } else {
      sum = math.subtract(math.bignumber(sum), math.bignumber(ele))
    }
  })
  return toNonExponential(sum)
}

export function numberMul(...arg) {
  let sum = 1
  arg.forEach((ele, index) => {
    if (index === 0) {
      sum = math.multiply(math.bignumber(ele), math.bignumber(1))
    } else {
      sum = math.multiply(math.bignumber(sum), math.bignumber(ele))
    }
  })
  return toNonExponential(sum)
}

export function numberDiv(...arg) {
  let sum = 0
  arg.forEach((ele, index) => {
    if (index === 0) {
      sum = math.divide(math.bignumber(ele), math.bignumber(1))
    } else {
      sum = math.divide(math.bignumber(sum), math.bignumber(ele))
    }
  })
  return toNonExponential(sum)
}

